package com.humanres.activity;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.GlideUtil;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.ciko.code.http.Req.QryKnowledgeDocumentListEty;
import com.ciko.code.utils.ScreenUtil;
import com.ciko.code.utils.Util;
import com.ciko.code.views.photoview.HackyViewPager;
import com.ciko.code.views.photoview.PhotoViewAttacher;
import com.mywork.R;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;


/**
 * @Project： 政企书屋
 * @Title：CloudReadActivity.java
 * @Description： 云阅读页面
 * @Author：Administrator
 * @Date：2014年11月3日下午5:56:49
 */

public class CloudReadActivity
		extends Activity
		implements
		OnClickListener, PhotoViewAttacher.OnViewTapListener
{
	private static final SimpleDateFormat sdf      = new SimpleDateFormat("HH:mm", Locale.CHINA);
	private boolean                       showInfo = true;
	private ImageView                     ivTitleBack;
	private TextView                      tvTitle, tvTime, tvLongIntro, tvName;

	private View                          topLayout, bottomLayout;
	private HackyViewPager                viewPager;
	private MyPagerAdapter                pagerAdapter;
	private HashMap<Integer, View>        views;
	private PhotoViewAttacher             attacher;
	private Context                       context;

	private QryKnowledgeDocumentListEty qryKnowledgeDocumentListEty;
	private String mTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//隐藏状态栏
		//getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		//		WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.cloudread);
		context=this;
		if (getIntent().hasExtra("QryKnowledgeDocumentListEty"))
		{
			qryKnowledgeDocumentListEty=(QryKnowledgeDocumentListEty)getIntent().getSerializableExtra("QryKnowledgeDocumentListEty");
			mTitle=qryKnowledgeDocumentListEty.getTitle();
		}
		else
		{
			finish();
		}
		ScreenUtil.GetInfo(context);
//		ImageUtil.destroyImageLoader();
//		ImageUtil.initImageLoader_low(this);

		findViews();
		setListeners();
		initData();
		initAnimation();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
//		ImageUtil.destroyImageLoader();
//		ImageUtil.initImageLoader_normal(this);
//		ImageLoader.getInstance().clearMemoryCache();
		if (null != attacher) attacher.cleanup();
	}

	private class MyPagerAdapter
			extends
			PagerAdapter
	{
		PhotoViewAttacher attacher;

		@Override
		public int getCount() {
			return qryKnowledgeDocumentListEty.getPages();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View view = views.get(position);
			if (view == null)
			{
				view = CloudReadActivity.this.getLayoutInflater().inflate(R.layout.cloudread_item, null);
				final ImageView img = (ImageView) view.findViewById(R.id.cloudread_item_img);
				final ImageView ivLoading = (ImageView) view.findViewById(R.id.cloudread_item_loading_img);
				final View failLayout = view.findViewById(R.id.cloudread_item_fail_layout);
				final String url = appendImageUrl(qryKnowledgeDocumentListEty.getPdfUrl(), position + 1);
				//				System.out.println("ViewPager --> position:"+position+",url:"+url);
				attacher = new PhotoViewAttacher(img);
				attacher.setOnViewTapListener(CloudReadActivity.this);
				failLayout.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View arg0) {
						loading(img, ivLoading, failLayout, url, attacher);
					}
				});
				loading(img, ivLoading, failLayout, url, attacher);
				views.put(position, view);
			}
			if (view.getParent() != null)
			{
				container.removeView(view);
			}
			container.addView(view);
			return view;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}
	}

	private void loading(final ImageView img, final ImageView loading, final View fail, final String url, final PhotoViewAttacher attacher) {
		img.setVisibility(View.GONE);
		fail.setVisibility(View.GONE);
		loading.setVisibility(View.VISIBLE);
		final AnimationDrawable drawable = (AnimationDrawable) loading.getBackground();
		drawable.start();

		GlideUtil.load(context,url,img,new RequestListener<String, GlideDrawable>() {
			@Override
			public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
//                              Toast.makeText(getApplicationContext(), "资源加载异常", Toast.LENGTH_SHORT).show();
				Util.showToast(CloudReadActivity.this, "加载失败");
				img.setVisibility(View.GONE);
				loading.setVisibility(View.GONE);
				fail.setVisibility(View.VISIBLE);
				return false;
			}

			//这个用于监听图片是否加载完成
			@Override
			public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
//                              Toast.makeText(getApplicationContext(), "图片加载完成", Toast.LENGTH_SHORT).show();
				drawable.stop();
				img.setVisibility(View.VISIBLE);
				loading.setVisibility(View.GONE);
				attacher.update();
				return false;
			}
		});

	}

	private class PagerChangeListener
			implements
			OnPageChangeListener
	{
		@Override
		public void onPageScrollStateChanged(int state) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {
			//			System.out.println("ViewPager onPageSelected-->"+arg0);
			final ImageView img = (ImageView) views.get(arg0).findViewById(R.id.cloudread_item_img);
			img.setScaleType(ScaleType.FIT_XY);
			PhotoViewAttacher attacher = new PhotoViewAttacher(img);
			attacher.setOnViewTapListener(CloudReadActivity.this);
			attacher.update();

			tvTitle.setText(getTitle(arg0 + 1, qryKnowledgeDocumentListEty.getPages()));
			//tvTime.setText(sdf.format(new Date(System.currentTimeMillis())));
			if (null != attacher) attacher.update();
		}
	}

	private String getTitle(int position, int pages) {
		StringBuffer sb = new StringBuffer();
		sb.append(position);
		sb.append("/");
		sb.append(pages);
		sb.append("页");
		return sb.toString();
	}

	private String appendImageUrl(String url, int page) {
		StringBuffer sb = new StringBuffer(url);
		sb.append("?c=1&w=");
		final int dpi = ScreenUtil.densityDpi;
		int width = ScreenUtil.screenWidth > 1080 ? ScreenUtil.screenWidth : ScreenUtil.screenWidth * 2;
		System.out.println("当前屏幕密度：" + dpi);
		System.out.println("当前屏幕宽度：" + width);
		sb.append(width);
		sb.append("&h=");
		final int height = ScreenUtil.screenHeight > 1920 ? ScreenUtil.screenHeight : ScreenUtil.screenHeight * 2;
		System.out.println("当前屏幕高度：" + height);
		sb.append(height);
		sb.append("&p=");
		sb.append(page);
		return sb.toString();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void initData() {
		views = new HashMap<Integer, View>();

		showInfo = true;
		tvTitle.setText(getTitle(1, qryKnowledgeDocumentListEty.getPages()));
		tvName.setText(qryKnowledgeDocumentListEty.getTitle());
		//tvLongIntro.setText(file.shortDesc);
		//tvTime.setText(sdf.format(new Date(System.currentTimeMillis())));
		viewPager.setOnPageChangeListener(new PagerChangeListener());
		pagerAdapter = new MyPagerAdapter();
		viewPager.setAdapter(pagerAdapter);
	}

	private void findViews() {
		ivTitleBack = (ImageView) findViewById(R.id.cloudread_title_back);
		tvTitle = (TextView) findViewById(R.id.cloudread_title_name);
		//tvTime = (TextView) findViewById(R.id.cloudread_title_time);
		tvLongIntro = (TextView) findViewById(R.id.cloudread_bottom_long_intro);
		viewPager = (HackyViewPager) findViewById(R.id.cloudread_vp);
		tvName = (TextView) findViewById(R.id.common_header_name);

		topLayout = findViewById(R.id.cloudread_top_layout);
		bottomLayout = findViewById(R.id.cloudread_bottom_layout);
	}

	private void setListeners() {
		ivTitleBack.setOnClickListener(this);
		viewPager.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int i = v.getId();
		if (i == R.id.cloudread_title_back) {
			finish();
		}
	}

	private TranslateAnimation mShowTopAnimation;
	private TranslateAnimation mHideTopAnimation;
	private TranslateAnimation mShowBottomAnimation;
	private TranslateAnimation mHideBottomAnimation;

	private void initAnimation() {
		// 从自已-1倍的位置(屏幕顶部)移到自己原来的位置
		mShowTopAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		mHideTopAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f);
		mShowTopAnimation.setDuration(500);
		mHideTopAnimation.setDuration(500);

		// 从自已1倍的位置(屏幕底部)移到自己原来的位置
		mShowBottomAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		mHideBottomAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
		mShowBottomAnimation.setDuration(500);
		mHideBottomAnimation.setDuration(500);
	}

	private void updateView() {
		showInfo = !showInfo;
		if (showInfo)
		{
			topLayout.startAnimation(mShowBottomAnimation);
			bottomLayout.startAnimation(mShowTopAnimation);
			topLayout.setVisibility(View.VISIBLE);
			bottomLayout.setVisibility(View.VISIBLE);
		}
		else
		{
			topLayout.startAnimation(mHideBottomAnimation);
			bottomLayout.startAnimation(mHideTopAnimation);
			topLayout.setVisibility(View.GONE);
			bottomLayout.setVisibility(View.GONE);
		}
	}

	@Override
	public void onViewTap(View view, float x, float y) {
		updateView();
	}

}
